import { webSocket } from '@kit.NetworkKit';
import { common  } from '@kit.AbilityKit'

interface CbList {
  (event):void
}
class Ws {

  url: string;
  ws:webSocket.WebSocket | null = null;
  reconnecter: null | number
  msgCb: Array<CbList>= [];
  context: common.UIAbilityContext;

  constructor() {
      // 监听网络的变化 如果网络好了 尝试去保持链接
  }
  init(){
    if(!this.ws) {
      this.ws = webSocket.createWebSocket();
      this.ws.on('close',()=>{
          // this.reconnect()
      })
      this.ws.on('open',()=>{
        console.log('链接或者重连成功')
        clearInterval(this.reconnecter);
        this.sendHeartBeat() // 保持心跳包的发送
      })
      this.ws.on('message',(err,event)=>{
        // this.msgCb.forEach(item=>item(event))
        // this.msgCb(event)
        this.context.eventHub.emit('wsMessage', event)
      })

      this.ws.on('error', ()=>{
          this.reconnect()
      })
      console.log('开始执行链接')
      this.ws.connect(this.url)
    }
  }
  reconnect(){
    this.ws = null;
    this.reconnecter = setInterval(()=>{
      if(this.ws){
        clearInterval(this.reconnecter)
        return;
      }
      console.log('网络断开 开始尝试重连')
      this.init();
    },3000)
  }

  sendHeartBeat(){
    return false;
    if(this.ws) {
      setTimeout(()=>{
        (this.ws as  webSocket.WebSocket).send('ht');
        this.sendHeartBeat()
        console.log('心跳包发送')
      },20000)
    }
  }
  setUrl(url: string,context: common.UIAbilityContext){
    this.url = url;
    this.context = context;
    this.init();
  }
  onMessage(cb){
    this.msgCb.push(cb)
    // this.msgCb = cb;
  }
  offMessage(cb){
    this.msgCb =this.msgCb.filter(item=>item!=cb)
  }


}


const wsClient = new Ws();


export default wsClient;